package com.shanzmoo.platform.manage.api.web.sys;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.constant.ErrorCode;
import com.shanzmoo.core.domain.vo.AuthUserVo;
import com.shanzmoo.core.util.OcrUtil;
import com.shanzmoo.db.module.msys.entity.MSysUserEntity;
import com.shanzmoo.db.module.msys.service.IMSysUserService;
import com.shanzmoo.db.module.psys.domain.vo.MenuVO;
import com.shanzmoo.db.module.psys.entity.PSysUserEntity;
import com.shanzmoo.db.module.psys.service.IPSysMenuService;
import com.shanzmoo.db.module.psys.service.IPSysUserService;
import com.shanzmoo.platform.manage.api.domain.AuthUser;
import com.shanzmoo.platform.manage.api.domain.bo.LoginReqBO;
import com.shanzmoo.platform.manage.api.manager.JwtManager;
import com.shanzmoo.platform.manage.api.util.RedisKeyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@Api(tags = "系统管理-登录")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class LoginController {

    private final AuthenticationManager authenticationManager;
    private final JwtManager jwtManager;
    private final IPSysUserService sysUserService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public SHttpResponse<AuthUserVo> login(@Valid @RequestBody LoginReqBO loginReq) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginReq.getUsername(), loginReq.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);

            AuthUser authUser = BeanUtil.toBean(authentication.getPrincipal(), AuthUser.class);

            String jwt = jwtManager.createJWT(false, authUser.getUserId(), authUser.getUsername(),
                    authUser.getRoleIds(), authUser.getAuthorities(),
                    RedisKeyUtils.installSubectJwtKey(authUser.getUsername()));

            PSysUserEntity user = sysUserService.lambdaQuery()
                    .eq(PSysUserEntity::getUsername, loginReq.getUsername())
                    .one();

            AuthUserVo userVo = AuthUserVo.create(user, jwt);

            return SHttpResponse.ok(userVo);
        } catch (Exception e) {
            return SHttpResponse.fail(ErrorCode.NOT_AUTH_BAD_CREDENTIALS);
        }

    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public SHttpResponse<Boolean> logout() {
        try {
            // 从redis中删除jwt信息
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            jwtManager.invalidateJWT(request);
        } catch (SecurityException e) {
            return SHttpResponse.fail(Constant.ERRCODE_LOGIC, "退出异常");
        }
        return SHttpResponse.ok();
    }


}
